//给你一个链表的头节点 head 和一个特定值 x ，请你对链表进行分隔，使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 
//
// 你应当 保留 两个分区中每个节点的初始相对位置。 
//
// 
//
// 示例 1： 
//
// 
//输入：head = [1,4,3,2,5,2], x = 3
//输出：[1,2,2,4,3,5]
// 
//
// 示例 2： 
//
// 
//输入：head = [2,1], x = 2
//输出：[1,2]
// 
//
// 
//
// 提示： 
//
// 
// 链表中节点的数目在范围 [0, 200] 内 
// -100 <= Node.val <= 100 
// -200 <= x <= 200 
// 
// Related Topics 链表 双指针 👍 604 👎 0


package com.cjl.leetcode.editor.cn;
/**
 * [P86]_分隔链表
 * @author cjl
 * @date 2022-08-04 15:22:36
 */
public class P86_PartitionList{
      public static void main(String[] args) {
            //测试代码
           Solution solution = new P86_PartitionList().new Solution();
      }
      //力扣代码
      //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    /**
     *
     * @param head
     * @param x
     * @return
     */
    public ListNode partition(ListNode head, int x) {
        if(null == head){
            return head;
        }
        ListNode leHeadList =new ListNode();
        ListNode leList = null;
        ListNode greateList = null;
        ListNode greateHeaderList = new ListNode();
        while (null != head){
            if(head.val < x){
                if(null == leList){
                    leList = head;
                    leHeadList.next = leList;
                }else {
                    leList.next = head;
                    leList = leList.next;
                }
            }else {
                if(null == greateList){
                    greateList = head;
                    greateHeaderList.next = greateList;
                }else {
                    greateList.next = head;
                    greateList = greateList.next;
                }
            }
            head = head.next;
        }
        if(null == leList){
            return greateHeaderList.next;
        }
        if(null == greateList){
            return leHeadList.next;
        }
        greateList.next = null;
        leList.next = greateHeaderList.next;
        return leHeadList.next;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

  }